package com.pro.back.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pro.back.bean.Borrow;
import com.pro.back.bean.BorrowExample;
import com.pro.back.bean.Device;
import com.pro.back.bean.DeviceExample;
import com.pro.back.bean.bo.BorrowBO;
import com.pro.back.bean.common.ApiRes;
import com.pro.back.bean.po.BorrowPO;
import com.pro.back.bean.po.ReturnParam;
import com.pro.back.dao.BorrowMapper;
import com.pro.back.dao.DeviceMapper;
import com.pro.back.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author: jingwenjuan
 * @Description:
 * @Date: 2025-04-19
 */
@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 分页条件查询所有的借还记录
     * @param po
     * @return
     */
    @Override
    public ApiRes selectAllBorrow(BorrowPO po) {
        PageHelper.startPage(po.getPageNum(),po.getPageSize());
        List<BorrowBO> list = borrowMapper.selectAllBorrow(po);
        PageInfo<BorrowBO> info = new PageInfo<>(list);
        return new ApiRes(info);
    }

    /**
     * 1.新增借出记录
     *      1）查询该设备是否被借出，是的话，提示已经被借出
     *      2）查询当前用户是否有超时未还的设备，有的话提示该用户还有尚未归还的设备
     *      3) 设备不能在报修、检修、报废中
     * 2.新增借出记录，设备状态更改为借出状态
     */
    @Override
    @Transactional
    public ApiRes insertBorrow(Borrow borrow) throws ParseException {
        Device device = deviceMapper.selectByPrimaryKey(borrow.getDeviceId());
        if (device == null) {
            return new ApiRes(500,null,"该设备不存在，请重新选择设备！");
        }
        if (device.getBorrowStatus().equals("1")) {
            return new ApiRes(500,null,"该设备已经被借出，请重新选择设备！");
        }
        if (!device.getRepairStatus().equals("0")) {
            String s = device.getRepairStatus();
            String message = s.equals("1")?"该设备在报修中，请重新选择设备！":(s.equals("2")?"该设备在检修中，请重新选择设备！":"该设备已报废，请重新选择设备！");
            return new ApiRes(500,null,message);
        }

        BorrowExample example = new BorrowExample();
        example.createCriteria().andUserIdEqualTo(borrow.getUserId()).andStatusEqualTo("0");
        List<Borrow> list = borrowMapper.selectByExample(example);
        if (list!=null && list.size()>0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (Borrow borrow1 : list) {
                int days = differentDays( sdf.parse(borrow1.getBorrowDate()),new Date());
                if (days>14) return new ApiRes(500,null,"您还有超时未归还的设备，请先归还设备！");
            }
        }

        borrowMapper.insertSelective(borrow);
        device.setBorrowStatus("1");
        deviceMapper.updateByPrimaryKeySelective(device);

        return new ApiRes("success");
    }

    @Override
    public ApiRes delBorrow(Long id) {
        BorrowExample ex = new BorrowExample();
        ex.createCriteria().andIdEqualTo(id);
        borrowMapper.deleteByPrimaryKey(id);
        return new ApiRes("success");
    }

    /**
     * 归还设备: 归还的人必须是借的人
     * 1. 修改borrow表的status
     * 2. 修改设备表的借还状态
     */
    @Override
    @Transactional
    public ApiRes returnDevice(ReturnParam param) {
        Long userId = borrowMapper.selectByPrimaryKey(param.getBorrowId()).getUserId();
        if (!userId.equals(param.getUserId())) {
            return new ApiRes(500,null,"您不是借该设备的人，不能执行此操作！");
        }

        Device device = new Device();
        device.setId(param.getDeviceId());
        device.setBorrowStatus("0");
        deviceMapper.updateByPrimaryKeySelective(device);

        Borrow borrow = new Borrow();
        borrow.setDeviceId(param.getDeviceId());
        borrow.setId(param.getBorrowId());
        borrow.setRealReturnDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        borrow.setStatus("1");
        borrowMapper.updateByPrimaryKeySelective(borrow);

        return new ApiRes("success");
    }


    /**
     * date2比date1多的天数
     */
    public static int differentDays(Date date1,Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2) {  //同一年
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                if(i%4==0 && i%100!=0 || i%400==0)    {//闰年
                    timeDistance += 366;
                }else   {//不是闰年
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else {  //不同年
            return day2-day1;
        }
    }
}
